package com.alm.token.ui.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.CurrencyChangeData;
import com.alm.token.ui.data.bean.CurrencyChangeIndexData;
import com.alm.token.ui.data.bean.CurrencyChangeListData;
import com.alm.token.ui.data.bean.DrawIndexData;
import com.alm.token.ui.data.bean.MiningWalletTypeIndexData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.StakingMiningMoneyDrawIndexData;
import com.alm.token.ui.data.bean.StakingOrderAddData;
import com.alm.token.ui.data.bean.StakingOrderAppendData;
import com.alm.token.ui.data.bean.StakingOrderIndexData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.CurrencyChangeView;
import com.alm.token.ui.view.StakingView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LogUtil;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import baibeiwallet.Constant;
import baibeiwallet.event.getUserWalletEvent;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StakingTransformActivity extends BaseActivity implements TextWatcher, StakingView<RegisterData> {
    @BindView(R.id.rightItem)
    TextView rightItem;
    @BindView(R.id.img_bizhong1icon)
    ImageView imgBizhong1icon;
    @BindView(R.id.tv_bizhong1tv)
    TextView tvBizhong1tv;
    //    @BindView(R.id.ly_moneytyep1)
//    LinearLayout lyMoneytyep1;
//    @BindView(R.id.img_clickchange)
//    ImageView imgClickchange;
    @BindView(R.id.img_bizhong2icon)
    ImageView imgBizhong2icon;
    @BindView(R.id.tv_bizhong2tv)
    TextView tvBizhong2tv;
    @BindView(R.id.tv_moneymax)
    TextView tvMoneyMax;

    //    @BindView(R.id.ly_moneytyep2)
//    LinearLayout lyMoneytyep2;
    @BindView(R.id.edt_inputnumber)
    EditText edtInputnumber;

    @BindView(R.id.edt_mathnumber)
    EditText edtMathnumber;


    //    @BindView(R.id.tv_bizhongshow)
//    TextView tvBizhongshow;
    @BindView(R.id.tv_outmoneycommit)
    TextView tvOutmoneycommit;
    @BindView(R.id.tv_jiaoyifeimath)
    TextView tvJiaoyifeiMath;
    @BindView(R.id.tv_zhuanhuanmsg)
    TextView tvZhuanhuanMsg;

    @BindView(R.id.img_changebizhong)
    ImageView imgChangebizhong;
    @BindView(R.id.tv_bizhong1price)
    TextView tvBizhong1Price;
    @BindView(R.id.tv_bizhong2price)
    TextView tvBizhong2Price;
    @BindView(R.id.tv_bizhong1money)
    TextView tvBizhong1Money;
    @BindView(R.id.tv_bizhong2money)
    TextView tvBizhong2Money;

    @BindView(R.id.ly_selectid)
    LinearLayout lySelectid;

    StakingMiningMoneyDrawIndexData.DataBean.DrawIndexVoBean drawIndexVoBean;
    List<StakingMiningMoneyDrawIndexData.DataBean.DrawIndexVoBean.ToListBean> toList = new ArrayList<>();
    StakingMiningMoneyDrawIndexData.DataBean.DrawIndexVoBean.ToListBean toListBean;
    private double number = 0d;
    private String moneyType;
    private double pro;
    int finalI = 0;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_transform_staking;
    }

    @Override
    protected void initVariables() {
        moneyType = getIntent().getStringExtra("moneyType");
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.main_hint_conversion));
    }

    double money = 0.0000d;

    public void mathNumber(double number) {
        tvBizhong1Money.setText(CommonUtil.saveToPoint4WithNo(drawIndexVoBean.getMoney()) + "/" + drawIndexVoBean.getMinDraw());

        tvBizhong1Price.setText(getString(R.string.transform_hint_exchangerate)
                + ("\t1 " + drawIndexVoBean.getName() + " = " + CommonUtil.saveToPoint4WithNo(1 / drawIndexVoBean.getPro()))
                + " " + toListBean.getName());

        money = number * (1 / drawIndexVoBean.getPro());
        edtMathnumber.setText(CommonUtil.saveToPoint4WithNo(money));

        LogUtil.e("money * pro" + money * pro);
        tvJiaoyifeiMath.setText(":" + CommonUtil.saveToPoint8WithNo(money * pro) + toListBean.getName());
    }

    @Override
    protected void loadData() {
        preenter.getStakingMiningMoneyDrawIndexData(moneyType);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.rightItem, R.id.tv_outmoneycommit, R.id.tv_moneymax, R.id.ly_selectid})
    public void onViewClicked(View view) {
        if (view.getId() != R.id.rightItem && drawIndexVoBean == null) {
            return;
        }

        switch (view.getId()) {

            case R.id.tv_moneymax:
                number = drawIndexVoBean.getMoney();
                edtInputnumber.setText(CommonUtil.saveToPoint4WithNo(number) + "");
//                edtInputnumber.setText(number + "");
//                mathNumber(number);
                break;

            case R.id.rightItem:
//                Intent intent = new Intent(this, VipOrderListActivity.class);
//                intent.putExtra("intentType", 1);
//                startActivity(intent);
                break;
            case R.id.ly_selectid:
                if (EmptyUtils.isNotEmpty(toList)) {
                    if(EmptyUtils.isNotEmpty(popWindow)){
                        popWindow.dismiss();
                        popWindow=null;
                    }
                    showPopwindow();
                }
                break;

            case R.id.tv_outmoneycommit:
                if (number == 0) {
                    showToast(getString(R.string.conversioncurrency_hint1_warn3));
                    break;
                } else if (number < drawIndexVoBean.getMinDraw()) {
                    showToast(getString(R.string.currency_hint1_leastinput, String.valueOf(drawIndexVoBean.getMinDraw())));
                    break;
                }

                UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                sysMsgBean.setTitle(getString(R.string.conversioncurrency_hint1_warn4));
                sysMsgBean.setContent(
                        getString(R.string.conversioncurrency_hint1_warn8, CommonUtil.saveToPoint4WithNo(number),
                                "" + tvBizhong1tv.getText().toString(), tvBizhong2tv.getText().toString()));
                DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {

                    DialogUtils.enterPayPsw(this, (pwd1) -> {

                        //eth1 mio2
                        preenter.getStakingDrawMiningOrderMoneyData(pwd1, number + "", String.valueOf(drawIndexVoBean.getId()), String.valueOf(toListBean.getId()));
                    });
                });

//                    showToast(getString(R.string.conversioncurrency_hint1_warn5));
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence s, int i, int i1, int i2) {

        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 4) {
                s = s.toString().subSequence(0, s.toString().indexOf(".") + 5);
                edtInputnumber.setText(s);
                edtInputnumber.setSelection(s.length());
            }
        }
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            edtInputnumber.setText(s);
            edtInputnumber.setSelection(2);
        }

        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                edtInputnumber.setText(s.subSequence(0, 1));
                edtInputnumber.setSelection(1);
                return;
            }
        }

        number = Double.parseDouble(s != null ? (!s.toString().isEmpty() ? s.toString() : "0") : "0");
//
        if (number > drawIndexVoBean.getMoney()) {
            showToast(getString(R.string.conversioncurrency_hint1_warn6));
//            number = drawIndexVoBean.getMoney();
//            edtInputnumber.setText(CommonUtil.saveToPoint4WithNo(number) + "");
            edtInputnumber.setText("");
            return;
        }
        mathNumber(number);
    }

    @Override
    public void afterTextChanged(Editable s) {
//        showToast(s != null ? s.toString() : "");

    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserWalletEvent1(getUserWalletEvent userWalletEvent) {

    }

    @Override
    public void getData(RegisterData registerData) {
        showToast(registerData.getMsg());
        if (registerData.getStatus() == 0) {
            loadData();
        }
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.conversioncurrency_hint1_warn7));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();

    }

    @Override
    public void getStakingAddOrderData(StakingOrderAddData stakingOrderAddData) {

    }

    @Override
    public void getStakingCancelQueuingData(RegisterData registerData) {

    }

    @Override
    public void getStakingPayOrderData(RegisterData registerData) {

    }

    @Override
    public void getStakingOrderAppendData(StakingOrderAppendData appendData) {

    }

    @Override
    public void getStakingMiningMoneyDrawIndexData(StakingMiningMoneyDrawIndexData stakingMiningMoneyDrawIndexData) {
        if (stakingMiningMoneyDrawIndexData.getStatus() == 0) {

            if (EmptyUtils.isNotEmpty(stakingMiningMoneyDrawIndexData.getData()) &&
                    EmptyUtils.isNotEmpty(stakingMiningMoneyDrawIndexData.getData().getDrawIndexVo())) {
                drawIndexVoBean = stakingMiningMoneyDrawIndexData.getData().getDrawIndexVo();
                pro = stakingMiningMoneyDrawIndexData.getData().getPro();
                tvZhuanhuanMsg.setText(stakingMiningMoneyDrawIndexData.getData().getMsg());
                GlideApp.with(this).load(drawIndexVoBean.getIcon())
                        .error(R.drawable.icon_arctic).into(imgBizhong1icon);
                tvBizhong1tv.setText(drawIndexVoBean.getName());
                toList.clear();
                if (EmptyUtils.isNotEmpty(drawIndexVoBean.getToList())) {
                    toList.addAll(drawIndexVoBean.getToList());
                    toListBean = toList.get(finalI);
                    GlideApp.with(this).load(toListBean.getIcon())
                            .error(R.drawable.icon_arctic).into(imgBizhong2icon);
                    tvBizhong2tv.setText(toListBean.getName());
                }


                edtInputnumber.addTextChangedListener(this);
                number = 0d;
                edtInputnumber.setText("");
                mathNumber(number);
            }
        } else {
            showToast(stakingMiningMoneyDrawIndexData.getMsg());
        }
    }

    @Override
    public void getMiningWalletTypeIndexData(MiningWalletTypeIndexData miningWalletTypeIndexData) {

    }

    @Override
    public void getDrawIndexData(Object o) {

    }


    PopupWindow popWindow;

    private void showPopwindow() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.view_pop_selecter, null);
        LinearLayout ly_pop_body = popView.findViewById(R.id.ly_pop_body);

        if (EmptyUtils.isNotEmpty(toList)) {
            for (int i = 0; i < toList.size(); i++) {
                StakingMiningMoneyDrawIndexData.DataBean.DrawIndexVoBean.ToListBean coinBean = toList.get(i);

                View itemView = View.inflate(this, R.layout.item_pop_wallet, null);
                GlideApp.with(this)
                        .load(coinBean.getIcon())
                        .error(R.drawable.icon_arctic)
                        .into((ImageView) itemView.findViewById(R.id.img_bizhongicon));
                ((TextView) itemView.findViewById(R.id.name)).setText(coinBean.getName());
                ((TextView) itemView.findViewById(R.id.desc)).setVisibility(View.INVISIBLE);

                ((TextView) itemView.findViewById(R.id.money1)).setText(CommonUtil.saveToPoint4WithNo(coinBean.getMoney()));
                ((TextView) itemView.findViewById(R.id.money2)).setVisibility(View.INVISIBLE);

                finalI = i;
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toListBean = toList.get(finalI);
                        GlideApp.with(v.getContext()).load(toListBean.getIcon())
                                .error(R.drawable.icon_arctic).into(imgBizhong2icon);
                        tvBizhong2tv.setText(toListBean.getName());
                        number = 0d;
                        edtInputnumber.setText("");
                        mathNumber(number);
                        popWindow.dismiss();
                    }
                });
                ly_pop_body.addView(itemView);

            }
            ly_pop_body.setBackgroundColor(getResources().getColor(R.color.text_cccccc));
        }

        RelativeLayout outside = popView.findViewById(R.id.pop_outside);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        if (popWindow == null) {
            popWindow = new PopupWindow(popView, width, height);
            popWindow.setAnimationStyle(R.style.BottomToTopAnim);
//        popWindow.setFocusable(true);
            popWindow.setOutsideTouchable(true);// 设置同意在外点击消失
        }
        outside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}
